package bancosys.tec.rtm.diagnostician.rmi;

import java.io.ByteArrayOutputStream;
import java.rmi.RemoteException;

import bancosys.tec.rtm.diagnostician.DiagnosticianCase;
import bancosys.tec.rtm.diagnostician.report.DiagnosticianReportGenerator;

/**
 * Implementação default de DiagnosticianRMIService.
 * 
 * @author Evaristo
 * @version $Id:$ <b>Created on: </b> 04/06/2007
 */
public class DiagnosticianRMIServiceImpl implements DiagnosticianRMIService {

    private DiagnosticianCase diagnosticianCase;

    /**
     * Construtor de DiagnosticianRMIServiceImpl.
     * 
     * @param diagnosticianCase {@link DiagnosticianCase}
     */
    public DiagnosticianRMIServiceImpl(DiagnosticianCase diagnosticianCase) {
        this.diagnosticianCase = diagnosticianCase;
    }

    /**
     * Gera o report do diagnosticador.
     * 
     * @param diagnosticianReportGeneratorClassName String
     * @throws RemoteException e
     * @return byte[]
     */
    public byte[] generateReport(String diagnosticianReportGeneratorClassName) throws RemoteException {
        DiagnosticianReportGenerator diagnosticianReportGenerator;
        try {
            diagnosticianReportGenerator =
                    (DiagnosticianReportGenerator) Class.forName(diagnosticianReportGeneratorClassName).getConstructor().newInstance();
        } catch (InstantiationException e) {
            throw new RemoteException("Erro ao instanciar a classe \"" + diagnosticianReportGeneratorClassName
                    + "\" para gerar o report do diagnosticador.", e);
        } catch (IllegalAccessException e) {
            throw new RemoteException("Erro ao inicializar a classe \"" + diagnosticianReportGeneratorClassName
                    + "\" para gerar o report do diagnosticador.", e);
        } catch (ClassNotFoundException e) {
            throw new RemoteException("Erro, a classe \"" + diagnosticianReportGeneratorClassName
                    + "\" não foi localizada no Classpath para gerar o report do diagnosticador.", e);
        } catch (Throwable e) {
            throw new RemoteException("Erro ao tentar instanciar a classe \"" + diagnosticianReportGeneratorClassName
                    + "\" para gerar o report do diagnosticador.", e);
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            this.diagnosticianCase.executeDiagnostician(diagnosticianReportGenerator, byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (Throwable e) {
            throw new RemoteException("Erro ao gerar o Report do diagnosticador remotamente.", e);
        }
    }
}